home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: pseudo-random numbers
- Date: Wed, 10 Jan 96 00:14:37 GMT
- Organization: none
- Message-ID: <821232877snz@genesis.demon.co.uk>
- References: <17709D420S86.JJSTEP00@ukcc.uky.edu>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <17709D420S86.JJSTEP00@ukcc.uky.edu>
- JJSTEP00@ukcc.uky.edu "Jason Stephenson" writes:
-
- >I know what the c.l.c. FAQ says about pseudo-random numbers, so I wonder why
- >I seem to get "better" results with "rand() % n + 1" than I get when I use
- >"n * rand() / RAND_MAX + 1" Am I missing some parenthesis or something?
-
- Your code might overflow when calculating n * rand(). Use the versions in
- section 13.16 of the FAQ, they don't have this problem. You could also try
- the following which should give a even distribution:
-
-
- #include <stdlib.h>
-
- int randrange(int range)
-
- {
- const int threshold = RAND_MAX - RAND_MAX % range;
- const int divisor = RAND_MAX / range;
- int randval;
-
- while ((randval = rand()) >= threshold)
- ;
-
- return randval / divisor;
- }
-
-
- >Oh yeah, and I usually call "srand(clock())" once in the initialization of
- >my program.
-
- Bad idea. On some systems clock() returns values that start at zero at
- program startup resulting in a high chance of the same seed on repeated
- runs of the program. time() is better (although you don't strictly know
- what type time_t is).
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-